#define UNICODE
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>

// 波特率
long baudrate = 115200;

void flshr_help()
{
    printf("-b, --baudrate []\n");
    printf("-p, --port COM*\n");
    printf("-h, --help\n");
}

// 打开并返回串口句柄，如果出错返回null
HANDLE flshr_port(LPCWSTR name)
{
    if (name == NULL)
        return NULL;
    return CreateFile(name,
                      GENERIC_READ | GENERIC_WRITE,
                      0, NULL,
                      OPEN_EXISTING,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
}

HANDLE flshr_opt(LPWSTR line)
{
    if (line == NULL)
        return 0;

    LPWSTR *szArgList;
    int argCount;
    HANDLE hComm = NULL;

    szArgList = CommandLineToArgvW(line, &argCount);
    if (szArgList == NULL)
        return 0;

    for (int i = 0; i < argCount; ++i)
    {
        if (szArgList[i][0] == L'-')
        {
            switch (szArgList[i][1])
            {
            case L'h':
                flshr_help();
                break;
            case L'p':
                i++;
                if (szArgList[i] == NULL)
                {
                    wprintf(L"Serial port not specified!\n");
                    break;
                }
                hComm = flshr_port(szArgList[i]);
                if (hComm == INVALID_HANDLE_VALUE)
                {
                    wprintf(L"Failed to open serial port %s, error code: %d\n", szArgList[i], GetLastError());
                    hComm == NULL;
                }
                break;
            case L'b':
            wchar_t* endPtr;
            long tmpb;
            i++;
                if (szArgList[i] == NULL)
                {
                    wprintf(L"No baud rate specified!\n");
                    break;
                }
                tmpb = wcstol(szArgList[i], &endPtr, 10);
                if (*endPtr == L'\0') {
                    baudrate = tmpb;
                } else {
                    wprintf(L"Baud rate error!\n");
                }
            break;
            default:
                break;
            }
        }
    }

    return hComm;
}

// 控制台
int flshr_console(HANDLE hComm)
{

    return 0;
}

int main(int argc, char *argv[])
{
    HANDLE hComm; // 串口句柄

    hComm = flshr_opt(GetCommandLine());
    if (hComm == NULL)
    {
        return 0;
    }

    CloseHandle(hComm);
    return 0;
}
